// $Id: DQLQuery.java 41 2011-10-04 22:32:52Z huijzer@gmail.com $
package lime.common;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.Map;
import java.util.regex.Matcher;

import org.apache.commons.io.IOUtils;

public class DQLQuery {

	public static final String SELECT_ALL_CABINETS = "select_all_cabinets.dql";
	public static final String SELECT_GROUP_CLASSES = "select_group_classes.dql";
	public static final String SELECT_ALL_GROUPS = "select_all_groups.dql";
	public static final String SELECT_ALL_USERS = "select_all_users.dql";
	public static final String SELECT_ALL_WORKITEMS = "select_all_workitems.dql";

	@SuppressWarnings("unchecked")
	public static String get(String queryName) {
		return get(queryName, Collections.EMPTY_MAP);
	}
	
	public static String get(String queryName, Map<String, String> params) {
		InputStream in = DQLQuery.class.getResourceAsStream("/dql/" + queryName);
		String dqlStatement = null;
		try {
			dqlStatement = IOUtils.toString(in);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		String resolvedDqlStatement = resolveParameters(dqlStatement, params);
		
		return resolvedDqlStatement;
	}

	public static String resolveParameters(String unresolved, Map<String, String> params) {

		String resolved = unresolved;

		for (String key : params.keySet()) {

			String value = params.get(key);
			String regex = "\\$\\{" + key + "\\}";
			String replacement = Matcher.quoteReplacement(value);
			resolved = resolved.replaceAll(regex, replacement);

		}

		return resolved;

	}
}
